﻿/*
<configuration>
  <configSections>
    <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>
  </configSections>
  <unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
    <assembly name="testef"/>
    <assembly name="EntityFramework"/>
    <container>
      <register type="System.Data.Entity.DbContext" mapTo="testef.hongyuanmmContext">
        <lifetime type="transient"/>
      </register>
      <register type="System.Data.Entity.DbContext" mapTo="testef.hongyuanmmContext" name="abcd">
        <lifetime type="singleton"/>
      </register>
    </container>
  </unity>
</configuration>
 */


using System.Linq;
using System.Text;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;
namespace Framework.Data
{
    /// <summary>
    /// IocContainer (默认使用Unity实现)配置方法见top
    /// </summary>
    public class IocContainer
    {
        private static readonly UnityContainer Container;
        /// <summary>
        /// 静态构造器
        /// </summary>
        static IocContainer()
        {
            Container = new UnityContainer();
            Container.LoadConfiguration();
            DisplayIocRegist();
        }
        /// <summary>
        /// 解析T
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T Resolve<T>()
        {
            return Container.Resolve<T>();
        }
        /// <summary>
        /// 解析T by Key
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="resolveKey"></param>
        /// <returns></returns>
        public static T Resolve<T>(string resolveKey)
        {
            return Container.Resolve<T>(resolveKey);
        }

        /// <summary>
        /// 打印Container中的注册信息
        /// </summary>
        public static void DisplayIocRegist()
        {
            StringBuilder sbContainer = new StringBuilder();
            sbContainer.AppendFormat("\n容器中 {0} 个注册信息:", Container.Registrations.Count());
            foreach (ContainerRegistration item in Container.Registrations)
            {
                string regType = item.RegisteredType.Name;
                string mapTo = item.MappedToType.Name;
                string regName = item.Name ?? "[默认]";
                string lifetime = item.LifetimeManagerType.Name;
                mapTo = (mapTo != regType) ? " -> " + mapTo : string.Empty;
                sbContainer.AppendFormat("\n+ {0}{1}  '{2}'  {3}", regType, mapTo, regName, lifetime);
            }
            Common.LogHelper.Debug(sbContainer);
        }
    }
}
